package com.sls.game.supply.deal;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.FileTransferToString;
import com.sls.core.util.PropertiesUtil;
import com.sls.core.util.ServerDateAndTime;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.enfu.EnfuAreaDAO;
import com.sls.game.dao.enfu.EnfuGoodsDAO;
import com.sls.game.dao.enfu.EnfuGoodsDetailDAO;
import com.sls.game.dao.enfu.EnfuServerDAO;
import com.sls.game.parser.enfu.EnfuGoodsDetailResponse;
import com.sls.game.pojo.enfu.EnfuAreaInfo;
import com.sls.game.pojo.enfu.EnfuGoodsDetailInfo;
import com.sls.game.pojo.enfu.EnfuGoodsInfo;
import com.sls.game.pojo.enfu.EnfuServerInfo;

/**
 * 
 * @Description：恩付相关接口处理
 * @author Wangxuegang
 * @Date：2013-5-22
 * 
 */
public class EnfuServiceDeal {

	private static Logger log = Logger.getLogger(EnfuServiceDeal.class);

	/**
	 * 商品查询同步接口url拼装
	 * 
	 * @return
	 */
	public static String getUrlOfGoodsSyn() {
		// 商户号
		String merchantid = PropertiesUtil.getValue("enfu.server.merchantid",
				"enfu.properties").trim();
		// 密钥
		String secretKey = PropertiesUtil.getValue("enfu.server.secretKey",
				"enfu.properties").trim();
		// 访问地址
		String addressUrl = PropertiesUtil.getValue(
				"enfu.server.address.goodsSynchronized", "enfu.properties")
				.trim();
		String data = merchantid + secretKey;
		String sign = UtilMD5Encryption.createMD5EncryptionOfGB2312(data);
		StringBuilder sb = new StringBuilder();
		sb.append(addressUrl);
		sb.append("?");
		sb.append("merchantid=");
		sb.append(merchantid);
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);

		String result = sb.toString().trim();
		return result;
	}

	/**
	 * 恩付商品批量同步
	 * 
	 * @param list
	 * @param enfuGoodsDAO
	 * @param head
	 */
	public static void insertGoodsSynInfo(List<EnfuGoodsInfo> list,
			EnfuGoodsDAO enfuGoodsDAO, Head head, String operator) {
		for (EnfuGoodsInfo enInfo : list) {
			// 先查询数据表，看该商品是否存在，如果不存在做插入操作；如果存在，做更新操作
			String primaryId = null;
			primaryId = enfuGoodsDAO.queryByProductid(enInfo.getProductid());
			if (primaryId == null) { // 商品新增
				String id = UUID.randomUUID().toString();
				String inserttime = ServerDateAndTime.getNowDateTimeOfFormat();
				enInfo.setId(id);
				enInfo.setInserttime(inserttime);
				enInfo.setOperator(operator);
				enInfo.setIsAudit("0"); // 0:未审核 1：已审核
				try {
					enfuGoodsDAO.insert(enInfo);
				} catch (Exception e) {
					log.error("Service处理[" + head.getRequestId()
							+ "]的请求出现数据更新异常！", e);
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			} else { // 商品更新
				String updatetime = ServerDateAndTime.getNowDateTimeOfFormat();
				enInfo.setId(primaryId);
				enInfo.setUpdatetime(updatetime);
				enInfo.setOperator(operator);
				enInfo.setIsAudit("0"); // 0:未审核 1：已审核
				try {
					enfuGoodsDAO.update(enInfo);
				} catch (Exception e) {
					log.error("Service处理[" + head.getRequestId()
							+ "]的请求出现数据更新异常！", e);
					throw new ServerDisponseException(
							ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
							ExceptionCodeDes.ACCESS_DATABASE_ERROR
									.getDescription());
				}
			}
		}
	}

	/**
	 * 商品详细url拼装
	 * 
	 * @param originalGoodsId
	 * @return
	 */
	public static String assembleUrlOfGoodsDetail(String productid) {
		String address = PropertiesUtil.getValue(
				"enfu.server.address.goodsDetail", "enfu.properties").trim();
		String merchantid = PropertiesUtil.getValue("enfu.server.merchantid",
				"enfu.properties").trim();
		String secretKey = PropertiesUtil.getValue("enfu.server.secretKey",
				"enfu.properties").trim();
		String data = merchantid + productid + secretKey;
		String sign = UtilMD5Encryption.createMD5EncryptionOfGB2312(data);

		StringBuilder sb = new StringBuilder();
		sb.append(address);
		sb.append("?");
		sb.append("merchantid=");
		sb.append(merchantid);
		sb.append("&");
		sb.append("productid=");
		sb.append(productid);
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);
		String result = sb.toString().trim();
		return result;
	}

	/**
	 * 恩付--服务器数据表插入
	 * 
	 * @param srvInfoList
	 * @param enfuServerDAO
	 * @param operator
	 */
	private static void insertSrv(List<EnfuServerInfo> srvInfoList,
			EnfuServerDAO enfuServerDAO, String operator) {
		if (srvInfoList != null && srvInfoList.size() > 0) {
			for (EnfuServerInfo srvInfo : srvInfoList) {
				String primaryId = enfuServerDAO.queryGameServer(srvInfo);
				if (primaryId == null) { // 插入
					String id = UUID.randomUUID().toString();
					String inserttime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					srvInfo.setId(id);
					srvInfo.setInserttime(inserttime);
					srvInfo.setOperator(operator);
					try {
						enfuServerDAO.insert(srvInfo);
					} catch (Exception e) {
						log.error(e);
					}

				} else { // 更新
					String updatetime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					srvInfo.setId(primaryId);
					srvInfo.setUpdatetime(updatetime);
					srvInfo.setOperator(operator);
					try {
						enfuServerDAO.updateInfo(srvInfo);
					} catch (Exception e) {
						log.error(e);
					}
				}
			}
		}
	}

	/**
	 * 恩付--区域数据表插入
	 */
	private static void insertArea(List<EnfuAreaInfo> areaInfoList,
			EnfuAreaDAO enfuAreaDAO, String operator) {
		if (areaInfoList != null && areaInfoList.size() > 0) {
			for (EnfuAreaInfo areaInfo : areaInfoList) {
				String primaryId = enfuAreaDAO.queryGameArea(areaInfo);
				if (primaryId == null) { // 插入
					String id = UUID.randomUUID().toString();
					String inserttime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					areaInfo.setId(id);
					areaInfo.setInserttime(inserttime);
					areaInfo.setOperator(operator);
					try {
						enfuAreaDAO.insert(areaInfo);
					} catch (Exception e) {
						log.error(e);
					}
				} else { // 更新
					String updatetime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					areaInfo.setId(primaryId);
					areaInfo.setUpdatetime(updatetime);
					areaInfo.setOperator(operator);
					try {
						enfuAreaDAO.updateInfo(areaInfo);
					} catch (Exception e) {
						log.error(e);
					}
				}
			}
		}
	}

	/**
	 * 商品详细记录插入或者更新
	 * 
	 * @param gameInfoList
	 * @param enfuGoodsDAO
	 * @param operator
	 */
	private static void insertGameInfo(List<EnfuGoodsDetailInfo> gameInfoList,
			EnfuGoodsDetailDAO enfuGoodsDetailDAO, String operator) {
		if (gameInfoList != null && gameInfoList.size() > 0) {
			for (EnfuGoodsDetailInfo goodsInfo : gameInfoList) {
				String primaryId = enfuGoodsDetailDAO
						.queryProductDetailInfo(goodsInfo);
				if (primaryId == null) { // 插入
					String id = UUID.randomUUID().toString();
					String inserttime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					goodsInfo.setId(id);
					goodsInfo.setInserttime(inserttime);
					goodsInfo.setOperator(operator);
					goodsInfo.setDefinedproductid((int)(Math.random()*1000000) + "");
					goodsInfo.setIsAudit("0");
					try {
						enfuGoodsDetailDAO.insertInfo(goodsInfo);
					} catch (Exception e) {
						log.error(e);
					}
				} else { // 更新
					String updatetime = ServerDateAndTime
							.getNowDateTimeOfFormat();
					goodsInfo.setId(primaryId);
					goodsInfo.setUpdatetime(updatetime);
					goodsInfo.setOperator(operator);
					goodsInfo.setIsAudit("0");
					try {
						enfuGoodsDetailDAO.updateInfo(goodsInfo);
					} catch (Exception e) {
						log.error(e);
					}
				}
			}
		}
	}

	/**
	 * 商品详细处理
	 * 
	 * @param goodsInfo
	 * @param enfuServerDAO
	 * @param enfuAreaDAO
	 * @param enfuGoodsDAO
	 * @param operator
	 */
	@SuppressWarnings("unchecked")
	public static void dealGoodsDetail(EnfuGoodsInfo goodsInfo,
			EnfuServerDAO enfuServerDAO, EnfuAreaDAO enfuAreaDAO,
			EnfuGoodsDetailDAO enfuGoodsDetailDAO, String operator) {
		String supplyEncode = "GB2312";
		String productid = goodsInfo.getProductid();
		// 坚果网络商品详细访问Url
		String url = EnfuServiceDeal.assembleUrlOfGoodsDetail(productid);
		HttpClient httpClient = new HttpClient();
		try {
			String xmlStr = httpClient.doGet(url, supplyEncode);
			String resultXml = FileTransferToString.transferToString(xmlStr);
			Map<String, Object> map = EnfuGoodsDetailResponse
					.parseGoodsDetail(resultXml);
			// 服务器
			List<EnfuServerInfo> srvInfoList = (List<EnfuServerInfo>) map
					.get("srvInfoList");
			// 区域
			List<EnfuAreaInfo> areaInfoList = (List<EnfuAreaInfo>) map
					.get("areaInfoList");
			// 游戏名称
			List<EnfuGoodsDetailInfo> gameInfoList = (List<EnfuGoodsDetailInfo>) map
					.get("gameInfoList");
			// 
			List<EnfuGoodsDetailInfo> productinfoList = (List<EnfuGoodsDetailInfo>) map
					.get("productinfoList");
			if (gameInfoList == null) {
				gameInfoList = productinfoList;
			}

			insertSrv(srvInfoList, enfuServerDAO, operator);
			insertArea(areaInfoList, enfuAreaDAO, operator);
			insertGameInfo(gameInfoList, enfuGoodsDetailDAO, operator);
		} catch (Exception e) {
			log.error(e);
		}
	}
}
